package com.wjk.blogs.web;


import com.wjk.blogs.NotFoundException;
import com.wjk.blogs.po.Blog;
import com.wjk.blogs.service.BlogService;
import com.wjk.blogs.service.CommentService;
import com.wjk.blogs.service.TagService;
import com.wjk.blogs.service.TypeService;
import com.wjk.blogs.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class indexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/")
    public String index(Model model,
                        @PageableDefault(
                                size=15,
                                sort = {"updateTime"},
                                direction = Sort.Direction.DESC
                        ) Pageable pageable){
        model.addAttribute("page",blogService.listBlog(pageable));
        model.addAttribute("types",typeService.listTypeTop(6));
        model.addAttribute("tags",tagService.listTagTop(10));
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));
        return "index";
    }

    @PostMapping("/search")
    public String search(Model model,
                         @PageableDefault(
                                 size=10,
                                 sort = {"updateTime"},
                                 direction = Sort.Direction.DESC
                         )Pageable pageable,
                         @RequestParam String query){
        model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        Blog blog = blogService.getBlog(id);
        blog.setViews(blog.getViews()+1);
        blogService.saveBlog(blog);
        model.addAttribute("comments",commentService.listCommentByBlogId(id));
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    @GetMapping("/footer/newBlog")
    public String newBlogs(Model model) {
        model.addAttribute("newBlog", blogService.listRecommendBlogTop(4));
        return "_fragments :: newBlogList";
    }

    @PostMapping("/addEyes/{id}")
    public void views(@PathVariable Long id){
        Blog blog=blogService.getBlog(id);
        int views=blog.getViews();
        blog.setViews(++views);
    }


}
